﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Linq;
using System.Linq;
using System.Linq.Dynamic;
using System.Text;
using System.Xml;
using IntraVision.Xml;

namespace IntraVision.Web
{
    public class DictionaryController<TEntity,TDataContext>:ConfigurableController 
        where TEntity: class, new()
        where TDataContext : DataContext, new()
    {

        public DictionaryController()
            : base()
        {
            _TemplateCompiler.AddReference(typeof(TDataContext).Assembly.Location);
            _TemplateCompiler.AddUsing("Model");
        }

        public virtual void List()
        {
            LoadConfigurator();
            GenerateXml();

            TDataContext dc = new TDataContext();

            if (Request["json"] != null)
            {
                TEntity[] entities = dc.GetTable<TEntity>().ToArray();
                RenderJSON(entities);
            }
            else
            {
                ViewData["result"] = dc.GetTable<TEntity>().ToList();
                RenderHtml();
            }
        }

        public virtual void View()
        {
            TDataContext dc = new TDataContext();
            int id = 0;
            try
            {
                if (!Int32.TryParse(Request["id"], out id))
                    throw new Exception("Неправильный идентификатор");

                TEntity entity = dc.GetTable<TEntity>().Where("Id = @0", id).FirstOrDefault();
                RenderJSON(entity);
            }
            catch (Exception ex)
            {
                AJAXResult result = new AJAXResult(ex);
                result.Result = "Не удалось получить запись из БД.";
                result.Id = id.ToString();
                RenderJSON(result);
            }
        }


        public virtual void Update()
        {
            TDataContext dc = new TDataContext();
            int id = 0;
            try
            {
                if (!Int32.TryParse(Request["id"], out id))
                    throw new Exception("Неправильный идентификатор");

                TEntity TEntity = dc.GetTable<TEntity>().Where("Id = @0", id).FirstOrDefault();
                RequestHelper.InitializeFromRequest<TEntity>(Request, TEntity);
                dc.SubmitChanges();

                RenderJSON(TEntity);
            }
            catch (Exception ex)
            {
                AJAXResult result = new AJAXResult(ex);
                result.Result = "Обновление не удалось.";
                result.Id = id.ToString();
                RenderJSON(result);
            }
        }


        public virtual void Create()
        {
            TDataContext dc = new TDataContext();
            TEntity TEntity = new TEntity();
            try
            {
                RequestHelper.InitializeFromRequest<TEntity>(Request, TEntity);
                dc.GetTable<TEntity>().InsertOnSubmit(TEntity);
                dc.SubmitChanges();

                RenderJSON(TEntity);
            }
            catch (Exception ex)
            {
                AJAXResult result = new AJAXResult(ex);
                result.Result = "Добавление не удалось";
                RenderJSON(result);
            }
        }

        public virtual void Delete()
        {
            AJAXResult result = new AJAXResult(true);
            TDataContext dc = new TDataContext();
            int id = 0;
            try
            {
                if (!Int32.TryParse(Request["id"], out id))
                    throw new ArgumentException("Неправильный идентификатор");

                TEntity TEntity = dc.GetTable<TEntity>().Where("Id = @0", id).FirstOrDefault();
                dc.GetTable<TEntity>().DeleteOnSubmit(TEntity);
                dc.SubmitChanges();

                result.Id = id.ToString();
            }
            catch (Exception ex)
            {
                result.IsOK = false;
                result.Id = id.ToString();
                result.Result = "Удаление не удалось";
                result.Description = ex.Message;
            }
            RenderJSON(result);
        }
    }
}
